package com.lxp.eduService.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lxp.eduService.domain.EduSubject;
import com.lxp.eduService.domain.excel.SubjectLevel;
import com.lxp.eduService.service.EduSubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
//Excel监听器
public class ExcelListener extends AnalysisEventListener<SubjectLevel> {
    private EduSubjectService eduSubjectService;
    public ExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }



    @Override
    public void invoke(SubjectLevel subjectLevel, AnalysisContext analysisContext) {
        //读取每行执行的方法,读取到的数据封装到dataDemo去
        System.out.println(subjectLevel);
        String firstSubject = subjectLevel.getFirstLevel();//获取一二级目录的名称
        String secondSubject = subjectLevel.getSecondLevel();

        //查询一级目录是否已经有
        EduSubject eduFirstSubject=findFirst(firstSubject);
        if (eduFirstSubject==null) {//没有重复的话
            eduFirstSubject =new EduSubject();
            eduFirstSubject.setTitle(firstSubject);
            eduFirstSubject.setParentId("0");
            eduSubjectService.save(eduFirstSubject);//存入对象
        }

        String parentId=eduFirstSubject.getId();

        EduSubject eduSecondSubject=findSecond(secondSubject,parentId);

        //查询二级目录是否已经有  在同一个一级目录下 是否有重复的
        if (eduSecondSubject==null) {//没有重复的对象
            eduSecondSubject =new EduSubject();
            eduSecondSubject.setTitle(secondSubject);
            eduSecondSubject.setParentId(parentId);
            eduSubjectService.save(eduSecondSubject);//存入对象
        }

    }

    @Override//读取后执行的方法
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    public EduSubject findFirst(String firstSubject){
        QueryWrapper<EduSubject> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("title",firstSubject);
        queryWrapper.eq("parent_id",0);
        EduSubject first = eduSubjectService.getOne(queryWrapper);
        return first;
    }

    public EduSubject findSecond(String secondSubject,String parentId){
        QueryWrapper<EduSubject> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("title",secondSubject);
        queryWrapper.eq("parent_id",parentId);
        EduSubject first = eduSubjectService.getOne(queryWrapper);
        return first;
    }
}
